package com.mxdx.edu.util;

import java.util.HashMap;
import java.util.Map;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.aliyuncs.DefaultAcsClient;
import com.aliyuncs.IAcsClient;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsResponse;
import com.aliyuncs.profile.DefaultProfile;
import com.aliyuncs.profile.IClientProfile;
import com.mxdx.edu.common.log.AppLogger;

/**
 * 短信工具类
 * 
 * @author wangyuan
 *
 */

@Service
public class SmsUtil {

	@Value("${signName}")
	private String signName;

	@Value("${templateCode}")
	private String templateCode;

	@Value("${accessKeyId}")
	private String accessKeyId;

	@Value("${accessKeySecret}")
	private String accessKeySecret;

	static final String product = "Dysmsapi";
	static final String domain = "dysmsapi.aliyuncs.com";

	private static String FAILED = "Failed";
	private AppLogger logger = new AppLogger(SmsUtil.class);

	public String sendSms(String mobilePhone, String content) {
		logger.entry(null, "sendSms");
		Map<String, Object> logMap = new HashMap<>();

		String code = FAILED;
		System.setProperty("sun.net.client.defaultConnectTimeout", "10000");
		System.setProperty("sun.net.client.defaultReadTimeout", "10000");

		logMap.put("mobilePhone", mobilePhone);
		try {
			// 初始化acsClient,暂不支持region化
			IClientProfile profile = DefaultProfile.getProfile("cn-hangzhou",
					accessKeyId, accessKeySecret);
			DefaultProfile.addEndpoint("cn-hangzhou", "cn-hangzhou", product,
					domain);
			IAcsClient acsClient = new DefaultAcsClient(profile);

			// 组装请求对象-具体描述见控制台-文档部分内容
			SendSmsRequest request = new SendSmsRequest();
			request.setPhoneNumbers(mobilePhone);
			request.setSignName(signName);
			request.setTemplateCode(templateCode);
			request.setTemplateParam(String
					.format("{\"code\":\"%s\"}", content));

			SendSmsResponse response = acsClient.getAcsResponse(request);
			code = response.getCode();
			String message = response.getMessage();
			String requestId = response.getRequestId();
			String bizId = response.getBizId();

			logMap.put("code", code);
			logMap.put("bizId", bizId);
			logMap.put("message", message);
			logMap.put("requestId", requestId);
			logger.info(logMap);
		} catch (Exception e) {
			code = FAILED;
			e.printStackTrace();
			logger.error(logMap);
		}
		return code;
	}

}
